package com.example.foodisimportant.utils;

import android.media.Image;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DBUtil {
    private String id=null;
    private String name=null;
    private String pass=null;
    private String campus=null;
    public DBUtil(String i,String m,String p,String c){
        this.id=i;
        this.name=m;
        this.pass=p;
        this.campus=c;
    }

    private static Connection getSQLConnection(){
        Connection con=null;
        try{
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            con= DriverManager.getConnection("jdbc:jtds:sqlserver:/10.0.2.2:1433/costomer_information" ,"sa", "3019209411");
        }catch (Exception e){
            e.printStackTrace();
        }
        return con;
    }

    public String QuerySQL(String n, String p){
        String result="";
        try{
            Connection conn=getSQLConnection();
            String sql="select*from dbo.stu_information where ( convert(nvarchar(255),stu_name)='"+name+"'and  convert(nvarchar(255),stu_psd)='"+pass+"') or ( convert(nvarchar(255),stu_id)='"+name+"' and  convert(nvarchar(255),stu_psd)='"+pass+"') ";
            Statement stat = conn.createStatement();
            ResultSet rs = ((Statement) stat).executeQuery(sql);
            while (rs.next())
            {
                result= "1" ;
            }
            ((ResultSet) rs).close();
            conn.close();
        }catch (Exception e1){
            e1.printStackTrace();
            result +="查询数据异常！"+ e1.getMessage();
        }
        return result;
    }

    public boolean InsertSQL(String i, String n, String p,String c) throws SQLException {
        Connection conn=getSQLConnection();
        String sql="INSERT INTO dbo.stu_information(stu_id,stu_name,stu_psd,stu_campus) VALUES(?,?,?,?)";
        if (conn!=null){
            try{
                PreparedStatement pstmt=conn.prepareStatement(sql);
                pstmt.setString(1,i);
                pstmt.setString(2,n);
                pstmt.setString(3,p);
                pstmt.setString(4,c);
                int value=pstmt.executeUpdate();
                if(value>0){
                    return true;
                }
            }catch (Exception e2){
                e2.printStackTrace();
            }finally {
                conn.close();
            }
        }
        return false;
    }

}
